package com.webflux.controller;


import com.webflux.entity.ElasticSearchEntity;
import com.webflux.entity.UserEntity;
import com.webflux.service.ElasticSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import reactor.core.publisher.Flux;

import java.io.IOException;

@Controller
@RequestMapping("/elasticsearch")
public class ElasticSearchController {


    @Autowired
    private ElasticSearchService elasticSearchService;

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public void create() throws IOException {
        elasticSearchService.createIndex();
    }


    @RequestMapping(value = "/createDocument", method = RequestMethod.GET)
    public void createDocument() throws IOException {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(2);
        userEntity.setPhone("琴酒");
        userEntity.setPassword("gin");
        elasticSearchService.createDocument("t_user", new ElasticSearchEntity(userEntity));
    }


    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public void find() throws IOException {
        elasticSearchService.find();
    }


    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    public void findAll() throws IOException {
        elasticSearchService.searchDocument();
    }


    @RequestMapping(value = "/findMatch", method = RequestMethod.GET)
    public void findMatch() throws IOException {
        elasticSearchService.queryMatch();
    }


    @RequestMapping(value = "/createQueryTerms", method = RequestMethod.GET)
    public void createQueryTerms(@RequestParam(value = "keyword", required = false) String keyword,
                                 @RequestParam(value = "page") Integer page,
                                 @RequestParam(value = "size") Integer size) {
        elasticSearchService.queryMatchDivided(keyword, page, size);
    }


    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Flux<UserEntity> test(String keyword) throws Exception {
//        elasticSearchService.createMapping("t_user","username");
        return elasticSearchService.findMatch(keyword);
//        return elasticSearchService.findAll(keyword);
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    public Flux<UserEntity> queryPage(@RequestParam(value = "keyword", required = false) String keyword,
                                 @RequestParam(value = "page") Integer page,
                                 @RequestParam(value = "size") Integer size) {
       return elasticSearchService.queryPage(keyword, page, size);
    }
}
